package org.dant.ant.extension.net.processors;

import java.io.*;
import java.util.*;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
import org.dant.ant.extension.tasks.internal.RemoteResponse;
import org.dant.ant.extension.utils.StringUtils;
import org.dant.apache.tools.ant.taskdefs.Execute;

public class StartJavaApp extends StartApp {

    private String[] jcmdl;
    private String javacmdline;
  
    public void setCommandline(String[] c) {
        this.jcmdl = c;
        javacmdline = StringUtils.convert2String(jcmdl);
    }

    protected Execute prepareExec() throws BuildException {
        if (dir == null) {
            dir = getProject().getBaseDir();
        }
    
        Execute exe = new Execute(createHandler(), createWatchdog());
        exe.setTask(this);
        exe.setExpectList(expectlist);
        exe.setResultsList(resultsList);
        exe.setAntRun(getProject());
        exe.setWorkingDirectory(dir);
        exe.setVMLauncher(vmLauncher);

        exe.setNewenvironment(newEnvironment);
        exe.setEnvironment(envs);
    
        exe.setCommandline(StringUtils.convert2LocalJavaCmd(jcmdl));
        return exe;
    }

    public String getProcessKey() {
        return javacmdline;
    }

    public void run() {
        RemoteResponse results = new RemoteResponse();
    
        Execute exe = prepareExec();
        int rc = -1;
        try {
            rc = exe.execute();
            if (exe.killedProcess()) {
                log("Timeout: killed the sub-process", Project.MSG_WARN); 
            }
        } catch (IOException e) {
            results.setSuccess(false);
            results.setResult("Exception: " + e.toString());
        }

        if (rc != 0) { 
            if (failOnError) {
                results.setSuccess(false);
                results.setResult("Java returned: " + rc + " location " + location);
            } else {
                log("Java Result: " + rc, Project.MSG_ERR);
            }
        }
        if (results.getResult() != null
            && !results.getResult().equals("")
            && !results.getResult().equals("N/A")) {
            resultsList.add(results);
        }
    }
}
